package com.zhangxu.junior.service.impl;

import com.zhangxu.junior.domain.Course;
import com.zhangxu.junior.domain.Student;
import com.zhangxu.junior.domain.StudentCourse;
import com.zhangxu.junior.mapper.StudentCourseMapper;
import com.zhangxu.junior.mapper.StudentMapper;
import com.zhangxu.junior.service.IStudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * @Author zhang xu
 * @Date 2022/6/20 15:52
 * @PackageName:com.zhangxu.junior.service.impl
 * @ClassName: StudentServiceImpl
 * @Description: TODO
 * @Version 1.0
 */
@Service
public class StudentServiceImpl implements IStudentService {

    @Autowired
    StudentMapper studentMapper;

    @Autowired
    StudentCourseServiceImpl studentCourseService;

    @Autowired
    CourseaService courseaService;



    @Override
    public List<Student> selectStudentList(Student student) {
        return studentMapper.selectStudentList(student);
    }

    @Override
    public boolean deleteStudentByIds(Long[] ids) {
        if(studentMapper.deleteStudentByIds(ids) >0){
            return true;
        }
        return false;
    }

    @Override
    public boolean insertStudent(Student student) {
        if(studentMapper.insertStudent(student) > 0){
            return true;
        }
        return false;
    }

    @Override
    public boolean updateStudent(Student student) {
        if(studentMapper.updateStudent(student) > 0){
            studentCourseService.delteStudentCourse(student.getId());

            for (Long courseId : student.getCourseIds()) {
                StudentCourse studentCourse = new StudentCourse();
                studentCourse.setStudentId(student.getId());
                studentCourse.setCourseId(courseId);
                studentCourseService.insertStudentCourse(studentCourse);
            }

            return true;
        }
        return false;
    }

    @Override
    @Transactional
    public Student selectStudentDetail(Student student) {

        //根据学生id查询中间表中所有的课程id
        StudentCourse studentCourse = new StudentCourse();
        studentCourse.setStudentId(student.getId());
        List<StudentCourse> studentCourses = studentCourseService.selectCourseBystudent(studentCourse);

        //根据所有课程查询出该学生所有的课程信息
        List<Long> courseIds = new ArrayList<>();
        for (StudentCourse studentCours : studentCourses) {
            courseIds.add(studentCours.getCourseId());
        }
        if(courseIds.size()>0){
            List<Course> courses = courseaService.selectCourseByIds(courseIds);
            student.setCourses(courses);
        }

        return student;
    }


}
